﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DonnetSpeech;
using FastReport;
using FastReport.Preview;
using MINERP.DisjoinProForOutShop.IView;
using MINERP.BLL.DisjoinProForOutShop;
using MINERP.MODEL.FoundationModel;
using System.Windows.Forms;
using MINERP.COM;
using MINERP.MODEL.DisjoinProForOutShop;
using MINERP.MODEL.OverOrder;
using System.Data;
using MINERP.DisjoinProForOutShop.Forms;
using Printing.Common;
using System.IO;
using System.Xml;
using System.Net.Mail;
using System.Net;
using System.Threading;

using System.Runtime.InteropServices;

using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;



namespace MINERP.DisjoinProForOutShop.Presenter
{
    public class MainPresenter
    {
        IFrmMain _view;
        DisJoinBLL2_Fuji _bll;
        int _PrePrintType = 0;//1--代表前面找印的是委外单，2---代表是帐单，0---代表前面还未打印任务单据
        Speech speech;
        public MainPresenter(IFrmMain view)
        {
            speech=new Speech();
            _view = view;
            _view.hashGrid = new Hashtable();
            _bll = new DisJoinBLL2_Fuji();
            reportOut.Load(Application.StartupPath + "\\PrintReportOutShop.frx");
            report.Load(Application.StartupPath + "\\PrintShopBill.frx");
            report1.Load(Application.StartupPath + "\\Report\\PrintShopBill.frx");
            report2.Load(Application.StartupPath + "\\PrintReportOutShop.frx");
            //InitialGrids();
        }

        public void AssinGrid(string barCode)//扫描条码
        {
            SubAreaType GridType;
            Grid_Info gridinfo = null;

            if (barCode.StartsWith("2") && barCode.Length == 10)
            {
                try
                {
                    //old
                    //Tb_OutShopGrid_Info gridInfo = _bll.AssinGrid(barCode, _view.OperateUserId);
                    //_view.RushOutShopGrid(gridInfo);

                    #region //new

                    try
                    {
                        gridinfo = _bll.ReceiveBarCode(barCode, _view.OperateUserId, _view.TechId, out GridType);
                        string zhuanStr = _bll.GetZhuanString(barCode);
                        SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
                        SpVoice Voice = new SpVoice();
                        if (zhuanStr == null)
                        {

                            Voice.Speak(gridinfo.GridNameNum, SpFlags);
                            //speech.Speak(gridinfo.GridName);
                        }
                        else
                        {
                            Voice.Speak(gridinfo.GridNameNum, SpFlags);//+ " " + zhuanStr, SpFlags);
                            Voice.Speak(zhuanStr, SpFlags);
                            //speech.Speak(gridinfo.GridName + " " + zhuanStr);
                        }
                    }
                    catch (CustomMsgException myex)
                    {
                        _view.ShowMsg(myex.Message);
                        return;
                        //throw;
                    }

                    switch (GridType)
                    {
                        case SubAreaType.Photo:
                            break;
                        case SubAreaType.OutShop: _view.RushOutShopGrid((OutShopGrid_Info)gridinfo);
                            break;
                        case SubAreaType.Shop: _view.RushShopGrid((ShopGrid_Info)gridinfo);
                            break;
                        default:
                            break;
                    }
                    #endregion

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("条码不正确，请重新输入!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public void ShowGridDetail()//双击格子时查看格子里的放的产品的详情
        {
            SubAreaType gridType = _bll.GetGridTypeByGridId(_view.CurrentGrid);
            switch (gridType)
            {
                case SubAreaType.Photo:
                    break;
                case SubAreaType.OutShop: _view.ShowOutShopGridDetail(_bll.GetOutShopGridProductListForList(_view.CurrentGrid));
                    _PrePrintType = 1;
                    break;
                case SubAreaType.Shop: _view.ShowShopGridDetail(_bll.GetShopGridProductList(_view.CurrentGrid));
                    _PrePrintType = 2;
                    break;
                default:
                    break;
            }
        }

        public void InitialGrids()//初始化格子
        {

            BindSubArea();
            GridSubArea_Info subShopAreaInfo = new GridSubArea_Info();
            GridSubArea_Info subOutShopAreaInfo = new GridSubArea_Info();
            switch (_view.ShowType)
            {
                case 0:
                    _view.InitailShopGrid(_bll.GetAllShopGrid(out subShopAreaInfo), subShopAreaInfo);
                    _view.InitialOutShopGrid(_bll.GetAllOutShopGrid(out subOutShopAreaInfo), subOutShopAreaInfo);
                    break;
                case 1:
                    _view.InitailShopGrid(_bll.GetAllShopGrid(out subShopAreaInfo), subShopAreaInfo);
                    break;
                case 2: _view.InitialOutShopGrid(_bll.GetAllOutShopGrid(out subOutShopAreaInfo), subOutShopAreaInfo);
                    break;
                default:
                    break;
            }
        }

        public void ClearCurrGrid()//清空当前格子
        {
            bool result = _bll.ClearGrid(_view.CurrentGrid);
            if (result)
            {
                _view.ClearGrid();
                //InitialGrids();
            }
            else
            {
                _view.ShowMsg("清空失败！");
            }
        }

        //public void PrintGrid()//打印当前格子
        //{
        //    SubAreaType gridType = _bll.GetGridTypeByGridId(_view.CurrentGrid);
        //    switch (gridType)
        //    {
        //        case SubAreaType.Photo:
        //            break;
        //        case SubAreaType.OutShop: PrintOutShopResultByGrid(_bll.GetOutShopGridProductList(_view.CurrentGrid), _view.CurrentGrid); _bll.MakeSureOut(_view.CurrentGrid);

        //            break;
        //        //case SubAreaType.Shop: PrintShopResultByGrid(_bll.GetShopGridProductList(_view.CurrentGrid), _view.CurrentGrid); _bll.OrderComplete(_view.TechId, _view.OperateUserId, _view.CurrentGrid);
        //        case SubAreaType.Shop:
        //            SHOP_Bill_Info sbinfo = _bll.OrderComplete(_view.TechId, _view.OperateUserId, _view.CurrentGrid);
        //            PrintBill(sbinfo);
        //            break;
        //        default:
        //            break;
        //    }
        //}
        public void PrintGrid()//打印当前格子
        {
            //FrmMarkSure frmSure = new FrmMarkSure();
            ////if (DialogResult.OK == frmSure.ShowDialog())
            ////{
            ////    this.IsPrintFahuo = frmSure.checkBoxIsPrint.Checked;
            ////    this.Cursor = Cursors.WaitCursor;

            ////}
            try
            {

                SubAreaType gridType = _bll.GetGridTypeByGridId(_view.CurrentGrid);

                switch (gridType)
                {

                    case SubAreaType.Photo:
                        break;
                    case SubAreaType.OutShop:
                        FrmMarkSure frmSure = new FrmMarkSure(0);
                        if (DialogResult.OK == frmSure.ShowDialog())
                        {
                            bool isClearOutGrid = false;
                            if (_view.OutSelectItems != null)//没点开格子打印
                            {
                                if (_view.OutSelectItems.Count < 1)
                                {
                                    MessageBox.Show("请选择要打印的产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return;
                                }

                                List<OverOrderView> listOOV =
                                    _view.OutSelectItems.Where(osi => osi.status == "已分堆在格子中").ToList();
                                if (listOOV.Count < 1)
                                {
                                    MessageBox.Show("请选择蓝色得记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return;
                                }


                                //PrintOutShopResultByGrid(listOOV, _view.CurrentGrid);
                                PrintOutShopResultByGridDEV(_bll.GetOutShopGridProductList(_view.CurrentGrid),
                                                        _view.CurrentGrid);
                                _bll.MakeSureOut(_view.CurrentGrid, listOOV, out isClearOutGrid, _view.OperateUserId);
                            }
                            else//点开格子打印
                            {
                                //PrintOutShopResultByGrid(_bll.GetOutShopGridProductList(_view.CurrentGrid),
                                //                         _view.CurrentGrid);
                                PrintOutShopResultByGridDEV(_bll.GetOutShopGridProductList(_view.CurrentGrid),
                                                         _view.CurrentGrid);
                                _bll.MakeSureOut(_view.CurrentGrid, _view.OperateUserId);
                                isClearOutGrid = true;

                            }

                            if (isClearOutGrid)
                            {
                                _view.ClearGrid();
                            }
                            // ClearCurrGrid(); 
                            //InitialGrids();
                        }
                        break;

                    case SubAreaType.Shop:
                        FrmMarkSure frmSure1 = new FrmMarkSure(1);
                        if (DialogResult.OK == frmSure1.ShowDialog())
                        {
                            _view.IsPrintFahuo = frmSure1.checkBoxIsPrint.Checked;
                            int intPay = 0;
                            try
                            {
                                intPay = Convert.ToInt32(frmSure1.numericUpDownPay.Text.Trim());
                            }
                            catch (Exception) { }


                            SHOP_Bill_Info sbinfo = null;
                            bool isClearGrid = true;
                            if (_view.ShopSelectItems != null)
                            {
                                if (_view.ShopSelectItems.Count < 1)
                                {
                                    MessageBox.Show("请选择要打印的产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return;
                                }
                                if (_view.CurrentGrid.SomeId != _view.ShopSelectItems.FirstOrDefault().OrderBagInfo.ShopID && _view.CurrentGrid.SomeId != _view.ShopSelectItems.FirstOrDefault().OrderBagInfo.OrderBagId)
                                {
                                    MessageBox.Show("请等待，正在打印帐单！注：如退出程序，帐单需要从帐务处打印!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return;
                                }
                                sbinfo = _bll.NewOrderComplete(_view.TechId, _view.OperateUserId, _view.CurrentGrid, _view.ShopSelectItems, out isClearGrid, _view.GetIsForcePrint, intPay);
                                //new                   

                            }
                            else
                            {
                                //if (_view.CurrentGrid.SomeId != _view.ShopSelectItems.FirstOrDefault().OrderBagInfo.ShopID)
                                //{
                                //    MessageBox.Show("打印不一致请关闭软件重新打开！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                //    return;
                                //}
                                //sbinfo = _bll.OrderComplete(_view.TechId, _view.OperateUserId, _view.CurrentGrid, _view.GetIsForcePrint);
                                //if (sbinfo == null)//检查是否打印空为已经打印
                                //{
                                //   // _view.ClearGrid();// 清空显示在格子中的信息
                                //    MessageBox.Show("没有产品在格子中，可能产品已经分片但未到达该节点，请确认，如没有请手动清空该格子", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                                //    return;
                                //}
                                //isClearGrid = true;
                                MessageBox.Show("请双击打开格子然后打印!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                return;
                            }
                            try
                            {
                                if (sbinfo != null)
                                {
                                   
                                    PrintBill(sbinfo);
                                    //PrintBillCrestly(sbinfo);
                                }
                                else
                                {
                                    isClearGrid = false;
                                }

                            }
                            catch (Exception ex)
                            {
                                isClearGrid = false;
                                WriteLogForCheck.WriteLogFile("打印帐单时出错:" + ex.Message);
                            }

                            //if (isClearGrid)
                            //{
                            //    ClearCurrGrid();
                            //}
                            //                InitialGrids();
                            if (isClearGrid)
                            {
                                //调用快递
                                if (_view.CurrentGrid.GridType == (int)GridType.Custom)
                                {
                                    //_view.CurrentGrid.SomeId =>tb_orderBagID
                                    FrmShipping frmShipping = new FrmShipping(_view.CurrentGrid.SomeId);
                                    frmShipping.ShowDialog();


                                }
                                _view.ClearGrid();


                            }
                        }
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        [DllImport("kernel32.dll")]
        public static extern int WinExec(string exeName, int operType);

        [DllImport("shell32.dll ")]
        public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);
        public void RePrint()//重新打印前面打印的东东
        {
            //Report report = new Report();
            string fr = Properties.Settings.Default.LastPrintPath;
            string type = fr.Split('|')[0];
            string path = fr.Split('|')[1];
            //path=@"D:\Projects\MINERP3.0\MINERP\MINERP.UserLogin\bin\Debug\报表文件\Y演示商户367\2010-7-16 16 04 03.frx";
            if (type.Equals("0"))//分堆
            {
                //report.LoadPrepared(path);
                //if (report.Prepare())
                //    report.ShowPrepared();
                //ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                    // new StringBuilder(path), new StringBuilder(string.Empty), 1);
                int billIndex = Properties.Settings.Default.BillIndex;
                MINERP.BLL.Statistics.BillIndexBLL2 _bll = new MINERP.BLL.Statistics.BillIndexBLL2();
                SHOP_Bill_Info shopbill = _bll.GetBillToView(billIndex);
                
                PrintBill(shopbill);

            }
            else
            {
                reportOut.LoadPrepared(path);
                if (reportOut.Prepare())
                    reportOut.ShowPrepared();

            }
            //report.Load(fr);
            //report.Show();
            //switch (_PrePrintType)
            //{

            //    case 0: MessageBox.Show("前面没有打印任何单据!");
            //        break;
            //    case 1://委外单

            //        try
            //        {
            //            report.Load(fr);
            //            report.Show();
            //        }
            //        catch (Exception ex)
            //        {

            //            MessageBox.Show("打印错误" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //        }

            //        break;
            //    case 2://帐单

            //        try
            //        {
            //            report.Load(fr);
            //            report.Show();
            //        }
            //        catch (Exception ex)
            //        {

            //            MessageBox.Show("打印错误" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //        }

            //        break;

            //    default:
            //        break;
            //}
        }

        /// <summary>
        /// 查询格子里商户的所有没有完成的订单信息
        /// </summary>
        public void SearchShopOrderInfo()
        {
            //int shopid = _view.CurrentGrid.SomeId;
            FrmSelectInfo frmS = new FrmSelectInfo(_view.ShopInGrid, _view.CurrentGrid.GridType);
            frmS.CurrShopId = _view.CurrentGrid.SomeId;
            frmS.StartTime = DateTime.MinValue;
            frmS.EndTime = DateTime.MinValue;
            frmS.ShowDialog();

        }
        public bool IsComplete(int inShopId)
        {
            int intNumShop = _bll.GetProductOrderProductByShopId(inShopId);
            int intNumGrid = _bll.GetProductOrderProductFromByShopId(inShopId);

            if (intNumShop == intNumGrid)
                if (intNumShop == 0)
                { return false; }
                else
                {
                    return true;
                }
            else
                return false;

        }
        public bool IsComplete(int inShopId, int inType)
        {
            if (inShopId == 115)
            {

            }
            int intNumShop = _bll.GetProductOrderProductByShopId(inShopId, inType);
            int intNumGrid = _bll.GetProductOrderProductFromByShopId(inShopId, inType);

            if (intNumShop == intNumGrid)
                if (intNumShop == 0)
                { return false; }
                else
                {
                    return true;
                }
            else
                return false;

        }
        public int IsCompleteInt(int inShopId)
        {
            int intNumShop = _bll.GetProductOrderProductByShopId(inShopId);
            int intNumGrid = _bll.GetProductOrderProductFromByShopId(inShopId);
            if (intNumShop == 0)
            {
                return -1;//该商户未有生产
            }
            else
            {
                if (intNumShop == intNumGrid)
                {
                    return 0;//生产完成
                }
                else
                {
                    return 1;//生产未完成
                }
            }

        }
        public int IsCompleteInt(int inShopId, int intType)
        {
            int intNumShop = _bll.GetProductOrderProductByShopId(inShopId);
            int intNumGrid = _bll.GetProductOrderProductFromByShopId(inShopId);
            if (intNumShop == 0)
            {
                return -1;//该商户未有生产
            }
            else
            {
                if (intNumShop == intNumGrid)
                {
                    return 0;//生产完成
                }
                else
                {
                    return 1;//生产未完成
                }
            }

        }

        Report report = new Report();
        Report report1 = new Report();
        #region helper methods
        //DSPrintShop dsshop = new DSPrintShop();
        //private void PrintBillCrestly(SHOP_Bill_Info sbinfo)
        //{
        //    try
        //    {
        //        // FrmPrint frm = new FrmPrint(sbinfo);
        //        //frm.ShowDialog();
        //        double PrinterAreas = 0;
        //        double PrinterCount = 0;
        //        int PhotoNum = 0;
        //        int ProductNum = 0;
        //        double DesginCount = 0;
        //        double ProductCount = 0;
        //        double AllCount = 0;
        //        double OtherCount = 0;
        //        bool IsNeedPrintMoney = sbinfo.Shop.IsNeedPrintUPrice;
        //        //DataTable tableTitle = dsshop.tableTitle();
        //        DataRow titleRow = dsshop.tableTitle.NewRow();
        //        titleRow["ShopName"] = sbinfo.Shop.ShopName;
        //        titleRow["Tel1"] = sbinfo.Shop.Tel1;
        //        titleRow["Tel2"] = sbinfo.Shop.Tel2;
        //        titleRow["ShopId"] = sbinfo.Shop.ShopId;
        //        titleRow["shopKeeper"] = sbinfo.Shop.ShopKeeper;
        //        titleRow["QQ"] = sbinfo.Shop.QQ;
        //        titleRow["BillId"] = sbinfo.BillId;
        //        titleRow["BillOrderCode"] = sbinfo.BillOrderCode;
        //        titleRow["CreateTime"] = sbinfo.CreateTime;
        //        titleRow["Adress"] = sbinfo.Shop.Address;
        //        if (IsNeedPrintMoney)
        //        {
        //            titleRow["Balance"] = sbinfo.ShopBalance;
        //            titleRow["BillCount"] = sbinfo.BillCount;
        //        }
        //        else
        //        {
        //            titleRow["Balance"] = 0;
        //            titleRow["BillCount"] = 0;
        //        }
        //        titleRow["IsNeedPrintMoney"] = IsNeedPrintMoney;


        //        titleRow["Salesman"] = sbinfo.Salesman;
        //        titleRow["CreditLevel"] = sbinfo.CreditLevel == null ? 0 : sbinfo.CreditLevel;
        //        dsshop.tableTitle.Rows.Add(titleRow);

        //        dsshop.tableTitle.TableName = "tableTitle";


        //        //DataTable tableDetail = CreateShopBillDetail();
        //        //DataTable tableSubDetail = CreateShopBillSubDetail();
        //        List<Bill_Detail_Info> detailList = sbinfo.List_Detail.ToList();

        //        foreach (Bill_Detail_Info billDetail in detailList)
        //        {
        //            ProductNum++;
        //            DataRow row = dsshop.tableDetail.NewRow();
        //            row["BillDetailId"] = billDetail.BillDetailId;
        //            row["OrderInfoCode"] = billDetail.OrderInfoCode;
        //            row["OrderProductName"] = billDetail.OrderProductName;
        //            row["CtmName"] = billDetail.CtmName;
        //            row["Remark"] = billDetail.Remark;
        //            row["OrderBagName"] = billDetail.OrderBagName;

        //            dsshop.tableDetail.Rows.Add(row);
        //            List<Bill_Detail_Detail_Info> subDetail = billDetail.ListDetail_Detail.ToList();
        //            foreach (Bill_Detail_Detail_Info detail in subDetail)
        //            {
        //                DataRow rowSub = dsshop.tableSubDetail.NewRow();
        //                rowSub["DetailName"] = detail.DetailName;
        //                rowSub["BillDetailId"] = billDetail.BillDetailId;
        //                rowSub["Spec"] = detail.Spec;
        //                rowSub["Num"] = detail.Num;
        //                rowSub["UnitPrice"] = detail.UnitPrice;
        //                if (IsNeedPrintMoney)
        //                {
        //                    rowSub["Count"] = detail.Count;
        //                }
        //                else
        //                {
        //                    rowSub["Count"] = 0;
        //                }

        //                rowSub["Area"] = detail.Area;
        //                rowSub["Type"] = detail.Type;
        //                if (detail.Type == (int)Bill_Detail_Detail_Type.NeedStatArea)
        //                {
        //                    PrinterAreas += detail.Area;
        //                    PrinterCount += detail.Count;
        //                    PhotoNum += detail.Num;
        //                }
        //                else if (detail.Type == (int)Bill_Detail_Detail_Type.UnNeedStatArea)
        //                {
        //                    ProductCount += detail.Count;
        //                    OtherCount += detail.Count;
        //                }
        //                else
        //                {
        //                    DesginCount += detail.Count;
        //                    OtherCount += detail.Count;
        //                }
        //                AllCount += detail.Count;
        //                dsshop.tableSubDetail.Rows.Add(rowSub);
        //            }
        //        }
        //        titleRow["PrinterAreas"] = PrinterAreas;
        //        titleRow["PrinterCount"] = PrinterCount;
        //        titleRow["ProductCount"] = ProductCount;
        //        titleRow["DesginCount"] = DesginCount;
        //        titleRow["PhotoNum"] = PhotoNum;
        //        titleRow["ProductNum"] = ProductNum;
        //        titleRow["AllCount"] = AllCount;
        //        titleRow["OtherCount"] = OtherCount;
        //        titleRow["CheckType"] = sbinfo.CheckType;
        //        titleRow["FactoryName"] = _view.WorkShopParas.WorkShopName;
        //        string information = "";
        //        string information2 = "";
        //        if (!string.IsNullOrEmpty(_view.WorkShopParas.Address))
        //        {
        //            information += "地址：" + _view.WorkShopParas.Address;
        //        }
        //        if (!string.IsNullOrEmpty(_view.WorkShopParas.QQ))
        //        {
        //            information += "  QQ：" + _view.WorkShopParas.QQ;
        //        }
        //        if (!string.IsNullOrEmpty(_view.WorkShopParas.CustomerTel))
        //        {
        //            information2 += "客服电话：" + _view.WorkShopParas.CustomerTel;
        //        }
        //        if (!string.IsNullOrEmpty(_view.WorkShopParas.FinanceTel))
        //        {
        //            information2 += " 财务电话：" + _view.WorkShopParas.FinanceTel;
        //        }
        //        titleRow["Information"] = information;
        //        titleRow["Information2"] = information2;
        //        dsshop.tableDetail.TableName = "tableDetail";
        //        dsshop.tableSubDetail.TableName = "tableSubDetail";
        //        CRPrintShop cr1 = new CRPrintShop();
        //        cr1.SetDataSource(dsshop);
        //        //crystalReportViewer1.ReportSource = cr1;
        //        //crystalReportViewer1.PrintReport();
        //        cr1.PrintOptions.PaperOrientation = PaperOrientation.Portrait;
        //        System.Drawing.Printing.PaperSize papersize = new System.Drawing.Printing.PaperSize();

        //        //cr1.PrintOptions.PaperSize = ;
        //        cr1.PrintToPrinter(1, true, 0, 0);
        //        //cr1.Load(Application.StartupPath+"\\"+"report\\CRPrintShop.rpt";
        //        //cr1.PrintToPrinter();

        //        string excelPath = Application.StartupPath + "\\报表文件\\" + sbinfo.Shop.ShopName;
        //        if (!Directory.Exists(excelPath))
        //        {
        //            Directory.CreateDirectory(excelPath);
        //        }
        //        string repPath = excelPath + "\\" + DateTime.Now.ToString().Replace(":", " ") + ".xls";
        //        cr1.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Excel, repPath);
        //        Properties.Settings.Default.LastPrintPath = "0|" + repPath;
        //        Properties.Settings.Default.Save();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("打印过程遇到问题，请查看本地报表或者财务报表，异常：" + ex.ToString());
        //    }

        //}
        /// <summary>
        /// 打印帐单
        /// </summary>
        /// <param name="sbinfo"></param>
        public void PrintBill(SHOP_Bill_Info sbinfo)
        {
            Properties.Settings.Default.BillIndex = sbinfo.BillId;
            try
            {
                double Para_TotalNum = 0;//照片总张数
                double Para_TotalAreas = 0;//照片总面积
                double Para_TotalCount = 0;//本期金额
                double Para_Sum = 0;//产品总数
                double Para_TotalPrintCount = 0;//输出金额
                double Para_TotalProductCount = 0;//产品金额

                #region//富士打印
                if (sbinfo.IsAssignByCustom)
                {

                }
                #endregion
                #region 组织打印数据

                bool IsNeedPrintMoney = sbinfo.Shop.IsNeedPrintUPrice;
                DataTable tableTitle = CreateShopBillTitle();
                DataRow titleRow = tableTitle.NewRow();
                titleRow["ShopName"] = sbinfo.Shop.ShopName;
                titleRow["Tel1"] = sbinfo.Shop.Tel1;
                titleRow["Tel2"] = sbinfo.Shop.Tel2;
                titleRow["ShopId"] = sbinfo.Shop.ShopId;
                titleRow["shopKeeper"] = sbinfo.Shop.ShopKeeper;
                titleRow["QQ"] = sbinfo.Shop.QQ;
                titleRow["BillId"] = sbinfo.BillId;
                titleRow["BillOrderCode"] = sbinfo.BillOrderCode;
                titleRow["CreateTime"] = sbinfo.CreateTime;
                titleRow["Adress"] = sbinfo.Shop.Address;
                titleRow["CheckOutType"] = sbinfo.CheckType;
                titleRow["Remark"] = sbinfo.Shop.Remark;
                //if (IsNeedPrintMoney)
                //{
                //    titleRow["Balance"] = sbinfo.ShopBalance;
                //    titleRow["BillCount"] = sbinfo.BillCount;
                //}
                //else
                //{
                //    titleRow["Balance"] = 0;
                //    titleRow["BillCount"] = 0;
                //}
                if (IsNeedPrintMoney)
                {
                    titleRow["Balance"] = sbinfo.ShopBalance;
                    titleRow["BillCount"] = sbinfo.BillCount;
                }
                else
                {
                    titleRow["Balance"] = 0;
                    titleRow["BillCount"] = 0;
                }
                titleRow["Salesman"] = sbinfo.Salesman;
                titleRow["CreditLevel"] = sbinfo.CreditLevel == null ? 0 : sbinfo.CreditLevel;
                tableTitle.Rows.Add(titleRow);

                tableTitle.TableName = "tableTitle";


                DataTable tableDetail = CreateShopBillDetail();
                DataTable tableSubDetail = CreateShopBillSubDetail();
                List<Bill_Detail_Info> detailList = sbinfo.List_Detail.ToList();

                foreach (Bill_Detail_Info billDetail in detailList)
                {
                    DataRow row = tableDetail.NewRow();
                    row["BillDetailId"] = billDetail.BillDetailId;
                    row["OrderInfoCode"] = billDetail.OrderInfoCode;
                    row["OrderProductName"] = billDetail.OrderProductName;
                    row["CtmName"] = billDetail.CtmName;
                    row["Remark"] = billDetail.Remark;
                    row["OrderBagName"] = billDetail.OrderBagName;

                    tableDetail.Rows.Add(row);
                    List<Bill_Detail_Detail_Info> subDetail = billDetail.ListDetail_Detail.ToList();
                    foreach (Bill_Detail_Detail_Info detail in subDetail)
                    {
                        DataRow rowSub = tableSubDetail.NewRow();
                        rowSub["DetailName"] = detail.DetailName;
                        rowSub["BillDetailId"] = billDetail.BillDetailId;
                        rowSub["Spec"] = detail.Spec;
                        rowSub["Num"] = detail.Num;
                        rowSub["UnitPrice"] = detail.UnitPrice;
                        rowSub["DetailRemark"] = detail.DetailRemark;
                        if (IsNeedPrintMoney)
                        {
                            rowSub["Count"] = detail.Count;
                        }
                        else
                        {
                            rowSub["Count"] = 0;
                        }

                        rowSub["Area"] = detail.Area;
                        rowSub["Type"] = detail.Type;
                        //if (!detail.DetailName.Contains("输出"))
                        //{
                        //    tableSubDetail.Rows.Add(rowSub);
                        //}
                        tableSubDetail.Rows.Add(rowSub);
                        if (detail.Type == 1)//是输出类型
                        {
                            Para_TotalNum += detail.Num;
                            Para_TotalAreas += detail.Area;
                            Para_TotalPrintCount += detail.Count;
                        }
                        else if (detail.Type == 0)
                        {
                            Para_TotalProductCount += detail.Count;
                        }
                        Para_TotalCount += detail.Count;
                    }
                    Para_Sum++;

                }
                if (!IsNeedPrintMoney)
                {
                     Para_TotalCount = 0;//本期金额
                   
                     Para_TotalPrintCount = 0;//输出金额
                     Para_TotalProductCount = 0;//产品金额
                }
                tableDetail.TableName = "tableDetail";
                tableSubDetail.TableName = "tableSubDetail";

                #region
                //DSPrintShop dsshop = new DSPrintShop();

                //dsshop.Tables.Add(tableTitle);
                //dsshop.Tables.Add(tableDetail);
                //dsshop.Tables.Add(tableSubDetail);
                //FrmPrint fp = new FrmPrint(sbinfo);
                //fp.Show();

                #endregion
                #endregion

                #region //获取发货信息
                DataTable tableBottom = CreateFahuoTable();
                DataRow bottomeRow = tableBottom.NewRow();
                if (_view.IsPrintFahuo)//打印发货信息
                {
                    Shop_DistributionInfo_Info distributionInfoInfo = new Shop_DistributionInfo_Info();
                    distributionInfoInfo = _bll.Get_DistributionInfoInfoByShopId(sbinfo.Shop.ShopId);
                    bottomeRow["ConsigneeName"] = "收货人：" + distributionInfoInfo.ConsigneeName;
                    bottomeRow["ConsigneeTelePhone"] = "收货电话：" + distributionInfoInfo.ConsigneeTelePhone;
                    bottomeRow["DistributionMode"] = "运输方式：" + distributionInfoInfo.DistributionMode;

                    bottomeRow["DistributionAddress"] = "货运指定点：" + distributionInfoInfo.DistributionAddress;
                    bottomeRow["BusTimetable"] = "收货单位：" + distributionInfoInfo.BusTimetable;
                    bottomeRow["ReMark"] = "备注：" + distributionInfoInfo.ReMark;
                    bottomeRow["Fahuodanwei"] = "发货单位：福州美神    电话：0591-87737187    勿压";
                    bottomeRow["Fahuodianhua"] = "勿压";
                }
                else
                {
                    bottomeRow["ConsigneeName"] = "";
                    bottomeRow["ConsigneeTelePhone"] = "";
                    bottomeRow["DistributionMode"] = "";

                    bottomeRow["DistributionAddress"] = "";
                    bottomeRow["BusTimetable"] = "";
                    bottomeRow["ReMark"] = "";
                    bottomeRow["Fahuodanwei"] = "";
                    bottomeRow["Fahuodianhua"] = "";
                }
                tableBottom.Rows.Add(bottomeRow);

                #endregion

                #region 打印报表
                DataSet set = new DataSet("ds");
                set.Tables.Add(tableTitle);
                set.Tables.Add(tableDetail);
                set.Tables.Add(tableSubDetail);
                set.Tables.Add(tableBottom);


                set.WriteXml(@"C:\Windows\xmldata\PrintShopBill.xml", XmlWriteMode.WriteSchema);
                report.RegisterData(tableTitle, "tableTitle");
                report.RegisterData(tableDetail, "tableDetail");
                report.RegisterData(tableSubDetail, "tableSubDetail");
                report.RegisterData(tableBottom, "tableBottom");


                //设置合计参数
                report.SetParameterValue("Para_TotalNum", Para_TotalNum);
                report.SetParameterValue("Para_TotalAreas", Para_TotalAreas);
                report.SetParameterValue("Para_TotalCount", Para_TotalCount);
                report.SetParameterValue("Para_Sum", Para_Sum);
                report.SetParameterValue("Para_TotalPrintCount", Para_TotalPrintCount);
                report.SetParameterValue("Para_TotalProductCount", Para_TotalProductCount);
                report.Prepare();
                report.Print();
                //FastReport.Export.Html.HTMLExport export = new FastReport.Export.Html.HTMLExport();


                //export.AllowOpenAfter = false;



                //string filePath = Application.StartupPath + "\\currPrint.html";
                //report.Export(export,filePath);


                #endregion

                #region 保存报表到本地
                report1.RegisterData(tableTitle, "tableTitle");
                report1.RegisterData(tableDetail, "tableDetail");
                report1.RegisterData(tableSubDetail, "tableSubDetail");
                //report1.SetParameterValue("Para_TotalNum", Para_TotalNum);
                //report1.SetParameterValue("Para_TotalAreas", Para_TotalAreas);
                //report1.SetParameterValue("Para_TotalCount", Para_TotalCount);
                //report1.SetParameterValue("Para_Sum", Para_Sum);
                //report1.SetParameterValue("Para_TotalPrintCount", Para_TotalPrintCount);
                //report1.SetParameterValue("Para_TotalProductCount", Para_TotalProductCount);
                report1.Prepare();
                string excelPath = Application.StartupPath + "\\报表文件\\" + sbinfo.Shop.ShopName;

                if (!Directory.Exists(excelPath))
                {
                    Directory.CreateDirectory(excelPath);
                }
                string repPath = excelPath + "\\" + DateTime.Now.ToString().Replace(":", " ") + ".fpx";
                report1.SavePrepared(repPath);
                Properties.Settings.Default.LastPrintPath = "0|" + repPath;
                Properties.Settings.Default.Save();
                #endregion
            }
            catch (Exception ex)
            {
                WriteLogForCheck.WriteLogFile(DateTime.Now + ":" + ex.StackTrace.ToString());
            }
        }
        Report reportOut = new Report();
        Report report2 = new Report();
        Thread threadSendMail;
        private void PrintOutShopResultByGrid(List<OverOrderView> productDetial, Grid_Info grid)
        {
            if (productDetial.Count < 1)
            {
                MessageBox.Show("未选中产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int BillID = 0;
            int BillIndex = 0;
            OutShopGrid_Info outGrid = (OutShopGrid_Info)grid;
            if (_bll.RecordOutShopBill(productDetial, _view.OperateUserId, outGrid.OutShop.OutShopId, out  BillID, out BillIndex))
            {

            }
            else
            {
                MessageBox.Show("账单未保存成功，请将打印单据交与财务手动录入！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            DataTable tableDetial = CreatePrintDataTable();
            productDetial = productDetial.OrderBy(oov => oov.OrderProductId).ToList();
            foreach (OverOrderView list in productDetial)
            {
                DataRow row = tableDetial.NewRow();
                row["OrderBagId"] = list.OrderBagId;
                row["OrderProductId"] = list.OrderProductId;
                row["OrderProductCode"] = list.OrderProductCode;
                row["BagCode"] = list.BagCode;
                row["BagName"] = list.BagName;
                row["OrderProductName"] = list.OrderProductName;

                row["CtmName"] = list.CtmName;
                row["ProductName"] = list.ProductName;
                row["PhotoNum"] = list.photoNum;
                row["ProductNum"] = list.ProductNum;
                row["ProductCode"] = list.ProductCode;
                row["CreateTime"] = list.CreateTime.ToString();
                row["PreFetchTime"] = list.PreFetchTime.ToString();
                row["OutRemark"] = list.OutRemark;
                row["FetchTime"] = list.FetchTime.ToString();
                row["FetchRemark"] = list.FetchRemark;
                row["CreateUserName"] = list.CreateUserName;
                row["ShopName"] = list.ShopName;

                row["Size"] = list.Size;
                tableDetial.Rows.Add(row);

            }
            tableDetial.TableName = "tableDetial";
            DataTable tableTop = CreateOutShopTop();
            DataRow newRow = tableTop.NewRow();

            newRow["OutShopId"] = outGrid.OutShop.OutShopId;
            //newRow["ShopId"] = outGrid.OutShop.OutShopId;
            newRow["OutShopName"] = outGrid.OutShop.OutShopName;
            newRow["Keeper"] = outGrid.OutShop.Keeper;
            newRow["Tel1"] = outGrid.OutShop.Tel1;
            newRow["Tel2"] = outGrid.OutShop.Tel2;
            newRow["City"] = outGrid.OutShop.City;
            newRow["Addr"] = outGrid.OutShop.Addr;
            newRow["Code"] = outGrid.OutShop.Code;
            newRow["Remark"] = outGrid.OutShop.Remark;
            newRow["Type"] = outGrid.OutShop.Type;
            newRow["BillID"] = BillID;
            newRow["BillIndex"] = BillIndex;
            tableTop.Rows.Add(newRow);
            tableTop.TableName = "tableTop";


            DataSet ds = new DataSet();
            ds.Tables.Add(tableDetial);
            ds.Tables.Add(tableTop);

            //reportOut.RegisterData(ds);
            reportOut.RegisterData(tableDetial, "tableDetial");
            reportOut.RegisterData(tableTop, "tableTop");
            //ds.WriteXml(Application.StartupPath + "\\PrintReportOutShop.xml");
            //ds.WriteXml(@"C:\Windows\xmldata\PrintReportOutShop.xml", XmlWriteMode.WriteSchema);

            //report.
            //reportOut.Design();

            //FastReport.Export.Xml.XMLExport export = new FastReport.Export.Xml.XMLExport();
            FastReport.Export.Html.HTMLExport export = new FastReport.Export.Html.HTMLExport();
            export.SinglePage = true;
            export.Navigator = true;
            export.Wysiwyg = true;
            export.Pictures = true;
            export.SubFolder = true;
            // reportOut.PrintSettings.ShowDialog = false;
            //report.Show();
            export.AllowOpenAfter = false;
            //reportOut.PrintSettings.ShowDialog = false;
            reportOut.Print();
            //reportOut.Prepare();
            string mailSendName = DateTime.Now.ToString("yyyyMMddHHmmss");
            //string filePath = @"C:\WINDOWS\xmlData\" + mailSendName + ".html";
            string filePath = Application.StartupPath + "\\发送邮件";


            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            //filePath += "\\" + mailSendName + ".html";
            string tempPath = filePath + "\\" + mailSendName + ".html";
            filePath += "\\" + mailSendName + ".files\\" + mailSendName + "main.html";

            reportOut.Export(export, tempPath);                   //导出临时邮件文件

            string para = grid.SomeId + "|" + filePath;
            ParameterizedThreadStart pts = new ParameterizedThreadStart(SendMail);
            threadSendMail = new Thread(new ParameterizedThreadStart(SendMail));

            threadSendMail.Start(para);
            ///保存报表


            //report1.Load(Application.StartupPath + "\\PrintReportOutShop.frx");
            // report1.RegisterData(ds);
            report2.RegisterData(tableDetial, "tableDetial");
            report2.RegisterData(tableTop, "tableTop");
            report2.Prepare();
            string excelPath = Application.StartupPath + "\\报表文件\\" + outGrid.OutShop.OutShopName;
            if (!Directory.Exists(excelPath))
            {
                Directory.CreateDirectory(excelPath);
            }
            string repPath = excelPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".fpx";
            report2.SavePrepared(repPath);
            Properties.Settings.Default.LastPrintPath = "1|" + repPath;
            Properties.Settings.Default.Save();


        }
        private void PrintOutShopResultByGridDEV(List<OverOrderView> productDetial, Grid_Info grid)
        {
            if (productDetial.Count < 1)
            {
                MessageBox.Show("未选中产品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int BillID = 0;
            int BillIndex = 0;
            OutShopGrid_Info outGrid = (OutShopGrid_Info)grid;
            if (_bll.RecordOutShopBill(productDetial, _view.OperateUserId, outGrid.OutShop.OutShopId, out  BillID, out BillIndex))
            {

            }
            else
            {
                MessageBox.Show("账单未保存成功，请将打印单据交与财务手动录入！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            
           
            string excelPath = Application.StartupPath + "\\报表文件\\" + outGrid.OutShop.OutShopName;
            if (!Directory.Exists(excelPath))
            {
                Directory.CreateDirectory(excelPath);
            }
             string repPath = excelPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            productDetial = productDetial.OrderBy(oov => oov.OrderProductId).ToList();
            //FrmOutShopReport frmDevReport = new FrmOutShopReport();
            XtraReport frmDevReport = new XtraReport();
            frmDevReport.LoadLayout(Application.StartupPath + "\\PrintReportOutShop.repx");
            frmDevReport.DataSource = productDetial;
            frmDevReport.ExportOptions.Xls.ShowGridLines=true;
            //frmDevReport.ExportOptions.Xls.Ignore65536RowsLimit = true;
            //frmDevReport.ExportOptions.Xls.UseNativeFormat = false;
            
                    
            frmDevReport.ExportOptions.Xls.SheetName = outGrid.OutShop.OutShopName;

            frmDevReport.PrintingSystem.ShowMarginsWarning = false;
            frmDevReport.ExportToXls(repPath);
            frmDevReport.PrintDialog();
            //frmDevReport.ShowPageSetupDialog();
            //frmDevReport.Print();

           
            


        }
        public void SendMail(object Paras)
        {
            try
            {
                int inOutShopId = Convert.ToInt32(((string)Paras).Split('|')[0]);
                string strPath = ((string)Paras).Split('|')[1];
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.Load("MINERP.OverEmail.XML");
                XmlNode root = xmlDoc.SelectSingleNode("Email");
                XmlNodeList nodeList = root.ChildNodes;
                XmlNode xn = nodeList[0];
                XmlElement xe = (XmlElement)xn;


                try
                {


                    //frm.Show();
                    string shopMailAddr = _bll.GetOutShopEmail(inOutShopId);
                    if (shopMailAddr != null && shopMailAddr != "@")
                    {
                        //string sendMailAddr = Properties.Settings.Default.OverSendMailBox;
                        //string smtpServer = Properties.Settings.Default.OverSmtpServer;
                        //string pwd = Properties.Settings.Default.OverMailPWD;
                        //string title = Properties.Settings.Default.OverTitle;
                        //string content = Properties.Settings.Default.OverContext;
                        string sendMailAddr = xe.GetAttribute("OverSendMailBox");
                        string smtpServer = xe.GetAttribute("OverSmtpServer");
                        string pwd = xe.GetAttribute("OverMailPWD");
                        string title = xe.GetAttribute("OverTitle");
                        string content = xe.GetAttribute("OverContext");
                        string userName = xe.GetAttribute("OverSendUserName");
                        string attachMent = strPath;


                        string[] sends = sendMailAddr.Split('@');
                        SmtpClient client = new SmtpClient(smtpServer);
                        client.UseDefaultCredentials = false;
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        client.Credentials = new NetworkCredential(userName, pwd);
                        MailMessage mmsg = new MailMessage(sendMailAddr, shopMailAddr);
                        mmsg.Subject = title;
                        mmsg.SubjectEncoding = Encoding.UTF8;
                        mmsg.Body = content;
                        mmsg.BodyEncoding = Encoding.UTF8;
                        mmsg.IsBodyHtml = true;
                        mmsg.Priority = MailPriority.High;
                        mmsg.Attachments.Add(new Attachment(attachMent));
                        client.Send(mmsg);
                        mmsg.Dispose();
                    }
                    else
                    {
                        MessageBox.Show("商户收件格式邮箱不正确！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }


                    //report.Dispose();
                }
                catch
                {
                    MessageBox.Show("请在委外处配置邮件信息！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                finally
                {
                    File.Delete(strPath);

                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void PrintShopResultByGrid(List<GridDetailBase> productDetail, Grid_Info grid)
        {
            ///创建明细表
            ShopGrid_Info shopGrid = (ShopGrid_Info)grid;
            DataTable tableDetial = CreatePrintDataTable();
            foreach (OverOrderView list in productDetail)
            {
                DataRow row = tableDetial.NewRow();
                row["OrderBagId"] = list.OrderBagId;
                row["OrderProductId"] = list.OrderProductId;
                row["OrderProductCode"] = list.OrderProductCode;
                row["BagCode"] = list.BagCode;
                row["BagName"] = list.BagName;
                row["OrderProductName"] = list.OrderProductName;
                row["CtmName"] = list.CtmName;
                row["ProductName"] = list.ProductName;
                row["ProductNum"] = list.ProductNum;
                row["ProductCode"] = list.ProductCode;
                row["ShopName"] = list.ShopName;

                tableDetial.Rows.Add(row);

            }
            tableDetial.TableName = "tableDetial";

            ///创建头部
            DataTable tableTop = CreateShopTop();
            DataRow newRow = tableTop.NewRow();
            newRow["ShopId"] = shopGrid.Shop.ShopId;
            newRow["shopName"] = shopGrid.Shop.ShopName;
            newRow["ShopId"] = shopGrid.GridId;
            newRow["shopKeeper"] = shopGrid.Shop.ShopKeeper;
            newRow["Tel1"] = shopGrid.Shop.Tel1;
            newRow["Tel2"] = shopGrid.Shop.Tel2;
            newRow["address"] = shopGrid.Shop.Address;

            tableTop.Rows.Add(newRow);
            tableTop.TableName = "tableTop";


            ///创建发货信息
            DataSet ds = new DataSet();
            ds.Tables.Add(tableDetial);
            ds.Tables.Add(tableTop);
            try
            {


                ds.WriteXml(@"C:\windows\xmlData\PrintReportShop.xml", XmlWriteMode.WriteSchema);

                Report report = new Report();
                report.Load(Application.StartupPath + "\\PrintReportShop.frx");
                report.Show();
            }
            catch (Exception)
            {

                //throw;
            }

        }
        /// <summary>
        /// 产品明细表
        /// </summary>
        /// <returns></returns>
        public DataTable CreatePrintDataTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OrderBagId", typeof(int));
            table.Columns.Add("OrderProductId", typeof(int));
            table.Columns.Add("OrderProductCode", typeof(string));
            table.Columns.Add("BagCode", typeof(string));
            table.Columns.Add("BagName", typeof(string));
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("ProductName", typeof(string));
            table.Columns.Add("ProductCode", typeof(string));
            table.Columns.Add("ProductNum", typeof(int));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("PreFetchTime", typeof(DateTime));
            table.Columns.Add("OutRemark", typeof(string));
            table.Columns.Add("FetchTime", typeof(DateTime));
            table.Columns.Add("FetchRemark", typeof(string));
            table.Columns.Add("CreateUserName", typeof(string));
            table.Columns.Add("Size", typeof(string));
            table.Columns.Add("PhotoNum", typeof(int));


            return table;
        }
        /// <summary>
        /// 商户信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("shopName", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("address", typeof(string));

            return table;

        }
        /// <summary>
        /// 为外商信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateOutShopTop()
        {
            DataTable table = new DataTable();
            table.Columns.Add("OutShopId", typeof(int));
            table.Columns.Add("OutShopName", typeof(string));
            table.Columns.Add("Keeper", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("City", typeof(string));
            table.Columns.Add("Addr", typeof(string));
            table.Columns.Add("Code", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("Type", typeof(bool));
            table.Columns.Add("BillID", typeof(string));
            table.Columns.Add("BillIndex", typeof(string));
            return table;

        }
        /// <summary>
        /// 创建title表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillTitle()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ShopName", typeof(string));
            table.Columns.Add("Tel1", typeof(string));
            table.Columns.Add("Tel2", typeof(string));
            table.Columns.Add("ShopId", typeof(int));
            table.Columns.Add("BillOrderCode", typeof(string));
            table.Columns.Add("shopKeeper", typeof(string));
            table.Columns.Add("QQ", typeof(string));
            table.Columns.Add("BillId", typeof(string));
            table.Columns.Add("CreateTime", typeof(DateTime));
            table.Columns.Add("Balance", typeof(double));
            table.Columns.Add("BillCount", typeof(double));
            table.Columns.Add("CreditLevel", typeof(int));
            table.Columns.Add("Salesman", typeof(string));
            table.Columns.Add("Adress", typeof(string));
            table.Columns.Add("CheckOutType", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            return table;

        }
        /// <summary>
        /// 创建明细产品
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("OrderInfoCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("OrderBagName", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建明细收费项目表
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillSubDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("DetailName", typeof(string));
            table.Columns.Add("Spec", typeof(string));
            table.Columns.Add("Num", typeof(int));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("Count", typeof(double));
            table.Columns.Add("Area", typeof(double));
            table.Columns.Add("Type", typeof(int));
            table.Columns.Add("DetailRemark", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建发货信息表
        /// </summary>
        /// <returns></returns>
        private DataTable CreateFahuoTable()
        {
            DataTable table = new DataTable("tableBottom");
            table.Columns.Add("ConsigneeName", typeof(string));
            table.Columns.Add("ConsigneeTelePhone", typeof(string));
            table.Columns.Add("DistributionAddress", typeof(string));
            table.Columns.Add("BusTimetable", typeof(string));//收货单位
            table.Columns.Add("ReMark", typeof(string));
            table.Columns.Add("DistributionMode", typeof(string));
            table.Columns.Add("Fahuodanwei", typeof(string));
            table.Columns.Add("Fahuodianhua", typeof(string));

            return table;
        }

        #endregion

        #region old
        /// <summary>
        /// 显示所有的格子信息(old)
        /// </summary>
        public void ShowAllGrids()
        {
            //int subAreaId = _view.CurrSubares.ID;
            //if (subAreaId > 0)
            //{
            //    _view.InitialOutShopGrid(_bll.GetAllGridBySubAreaId(subAreaId));
            //}
            //else
            //{
            //    MessageBox.Show("当前分区不可用！" + subAreaId.ToString(), "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    BindSubArea();
            //}
        }

        ///// <summary>
        ///// 查看格子里的产品列表信息(old)
        ///// </summary>
        //private void ShowGridProductsDetail()
        //{
        //    int gridId = _view.CurrentGrid.GridId;
        //    if (gridId > 0)
        //    {
        //        _view.ShowOutShopGridDetail(_bll.GetOutShopTaskList(gridId));
        //    }
        //}

        ///// <summary>
        ///// 查看此格子对应的商户的信息，以及此委外商户下的产品信息(old)
        ///// </summary>
        //public void ShowGridShopHead()
        //{


        //    int gridId = _view.CurrentGrid.GridId;
        //    if (gridId > 0)
        //    {
        //        _view.ShowOutShopInfo(_bll.GetGridInfoById(gridId).OutShop);
        //        _view.ShowOutShopGridDetail(_bll.GetOutShopTaskList(gridId));
        //    }
        //}

        /// <summary>
        /// 绑定所有可用的分区
        /// </summary>
        public void BindSubArea()
        {
            //List<PhotoSubarea_Info> subAreaList = _bll.GetAllSubArea();
            //if (subAreaList == null || subAreaList.Count == 0)
            //{
            //    MessageBox.Show("没有可用分区！");
            //    _view.Exit();
            //}
            //else if (subAreaList.Count == 1)//只有一个分区
            //{
            //    _view.CurrSubares = subAreaList[0];
            //    ShowAllGrids();
            //    MessageBox.Show("只有一个可用分区：" + subAreaList[0].SubareaName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            //}
            //else//多个分区
            //{
            //    _view.SelectSubArea(subAreaList);
            //}
            _view.CurrShopSubares = _bll.GetShopSubArea();
            _view.CurrOutShopSubares = _bll.GetOutShopSubArea();
        }

        ///// <summary>
        ///// 清空当前格子(old)
        ///// </summary>
        //public void ClearCurrentGrid()
        //{
        //    bool result = false;
        //    //try
        //    //{
        //    result = _bll.ClearGrid(_view.CurrentGrid.GridId);
        //    //}
        //    //catch (Exception ex)
        //    //{
        //    //    MessageBox.Show("清空失败：" + ex.Message, "警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);
        //    //    throw;
        //    //}
        //    if (result)
        //    {
        //        _view.ClearGrid();
        //    }
        //    else
        //    {
        //        MessageBox.Show("清空失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    }
        //}
        #endregion
        /// <summary>
        /// 
        /// </summary>
        public void ExportOutProduct()//d导出当前委外格子
        {
            if (_view.CurrentGrid == null)
            {
                return;
            }
            SubAreaType gridType = _bll.GetGridTypeByGridId(_view.CurrentGrid);

            switch (gridType)
            {
                case SubAreaType.Photo:
                    break;
                case SubAreaType.OutShop:
                    bool isClearOutGrid = false;
                    if (_view.OutSelectItems != null)
                    {
                        if (_view.OutSelectItems.Count < 1)
                        {
                            MessageBox.Show("请选择要打印的产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        List<OverOrderView> listOOV =
                            _view.OutSelectItems.Where(osi => osi.status == "已分堆在格子中").ToList();
                        if (listOOV.Count < 1)
                        {
                            MessageBox.Show("请选择蓝色得记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        //处理listOOV中的产品                           
                        //((OutShopUGrid)_view.hashGrid[_view.CurrentGrid.GridId]).GridName
                        string gridName = _view.CurrentGrid.GridName;
                        //string outShopName = ((OutShopUGrid) _view.hashGrid[_view.CurrentGrid.GridId]).OutShopName;
                        FrmExportOutProduct frmExportOutProduct = new FrmExportOutProduct(listOOV, gridName);
                        frmExportOutProduct.ShowDialog();

                    }
                    else
                    {
                        //PrintOutShopResultByGrid(_bll.GetOutShopGridProductList(_view.CurrentGrid),
                        //                         _view.CurrentGrid);
                        //_bll.MakeSureOut(_view.CurrentGrid);
                        //isClearOutGrid = true;
                        FrmExportOutProduct frmExportOutProduct = new FrmExportOutProduct(_bll.GetOutShopGridProductList(_view.CurrentGrid), _view.CurrentGrid.GridName);
                        frmExportOutProduct.ShowDialog();
                    }


                    break;

                case SubAreaType.Shop:
                    MessageBox.Show("只能导出委外数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    break;

                default:
                    break;
            }
        }
        public void ExportOutProduct2()//d导出当前委外格子
        {
            if (_view.CurrentGrid == null)
            {
                return;
            }
            SubAreaType gridType = _bll.GetGridTypeByGridId(_view.CurrentGrid);

            switch (gridType)
            {
                case SubAreaType.Photo:
                    break;
                case SubAreaType.OutShop:
                    bool isClearOutGrid = false;
                    if (_view.OutSelectItems != null)
                    {
                        if (_view.OutSelectItems.Count < 1)
                        {
                            MessageBox.Show("请选择要打印的产品!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        List<OverOrderView> listOOV =
                            _view.OutSelectItems.Where(osi => osi.status == "已分堆在格子中").ToList();
                        if (listOOV.Count < 1)
                        {
                            MessageBox.Show("请选择蓝色得记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        //处理listOOV中的产品                           
                        //((OutShopUGrid)_view.hashGrid[_view.CurrentGrid.GridId]).GridName
                        string gridName = _view.CurrentGrid.GridName;
                        //string outShopName = ((OutShopUGrid) _view.hashGrid[_view.CurrentGrid.GridId]).OutShopName;
                        FrmExportOutProduct frmExportOutProduct = new FrmExportOutProduct(listOOV, gridName);
                        frmExportOutProduct.ShowDialog();

                    }
                    else
                    {
                        //PrintOutShopResultByGrid(_bll.GetOutShopGridProductList(_view.CurrentGrid),
                        //                         _view.CurrentGrid);
                        //_bll.MakeSureOut(_view.CurrentGrid);
                        //isClearOutGrid = true;
                        FrmExportOutProduct frmExportOutProduct = new FrmExportOutProduct(_bll.GetOutShopGridProductList(_view.CurrentGrid), _view.CurrentGrid.GridName);
                        frmExportOutProduct.ShowDialog();
                    }


                    break;

                case SubAreaType.Shop:
                    MessageBox.Show("只能导出委外数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    break;

                default:
                    break;
            }
        }

    }
}
